package com.woniu.service.Impl.homePage;

import com.alibaba.fastjson.JSON;
import com.woniu.dao.homePage.AddressDao;
import com.woniu.entity.Address;
import com.woniu.service.homePage.IAddressService;
import com.woniu.util.ResData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 凌雨
 * @data 2023/3/9 10:38
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询用户收货地址
     * @param phone 用户的手机号
     * @return
     */
    @Override
    public ResData<?> queryAddressByPhone(String phone) {

        if ("null".equals(phone) || phone == null) {
            return new ResData<>().ok();
        }

        String address = redisTemplate.opsForValue().get("phone:" + phone);
        if (address != null){
            List<Address> addressList = JSON.parseArray(address, Address.class);
            return new ResData<>().ok(addressList);
        }

        List<Address> addressList = addressDao.queryAddressByPhone(phone);
        redisTemplate.opsForValue().set("address:" + phone, JSON.toJSONString(addressList), 30, TimeUnit.MINUTES);
        return new ResData<>().ok(addressList);
    }

    /**
     * 增加用户收货地址
     * @param address 用户的收货地址
     */
    @Override
    public ResData<?> saveAddress(Address address) {
        addressDao.insertAddress(address);
        return new ResData<>().ok();
    }

    /**
     * 删除用户收货地址
     * @param id 收货表的id
     */
    @Override
    public ResData<?> removeAddress(Integer id,String phone) {
        addressDao.deleteAddress(id,phone);
        return new ResData<>().ok();
    }

    /**
     * 修改用户地址
     * @param address 用户的收货地址
     */
    @Override
    public ResData<?> updateAddress(Address address) {
        addressDao.updateAddress(address);
        return new ResData<>().ok();
    }

}
